from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

import cherrypy
import db
import base64
from users import user

class usercontroller(object):
	lookup = None
	
	def __init__(self, lup):
		self.lookup = lup
	
	def index(self, msg=None):
		sess = db.getsession()
		print cherrypy.session['CMSUSER']
		u = sess.query(user).all()
		return self.lookup.get_template("users.html").render(users=u, msg=msg)
	index.exposed = True

	def submitlogin(self, userid, password):
		sess = db.getsession()
		try:
			u = sess.query(user).filter(user.USERID == userid).one()
		except:
			return  self.lookup.get_template("submitlogin.html").render(msg="User Not Found")
		if base64.b64decode(u.PASSWORD) == password:
			cherrypy.session['CMSUSER'] = user.USERID
			return self.lookup.get_template("submitlogin.html").render(msg="Logged In", loggedin=True)
		return self.lookup.get_template("submitlogin.html").render(msg="Incorrect Password")
	submitlogin.expose = True

	def edituser(self, userid=None):
		sess = db.getsession()
		if userid:
			u = sess.query(user).filter(user.USERID == userid).one()
			return self.lookup.get_template("edituser.html").render(u = u, table=db.user_table)
		else:
			return self.lookup.get_template("edituser.html").render(u = user(), table=db.user_table)
	edituser.exposed = True

	def saveuser(self, **kwargs):
		sess = db.getsession()
		print kwargs
		try:
			u = sess.query(user).filter(user.USERID == kwargs['USERID']).one()
		except:
			u = user()
			u.USERID = kwargs['USERID']
			sess.add(u)
			sess.flush()	

		for k in kwargs:
			if kwargs[k]:
				setattr(u, k, kwargs[k])
		if u.PASSWORD:
			u.PASSWORD = base64.b64encode(u.PASSWORD)
		if kwargs["JOIN"]:
			u.JOIN = parse_date(kwargs["JOIN"])	
		sess.flush()
		msg = "User ", u.USERID, " has been saved"

		return self.index(msg=msg)
		#return self.lookup.get_template("users.html").render(msg="User Saved", u = sess.query(user).all())
	saveuser.exposed = True


